package VLSys;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import javax.swing.table.DefaultTableModel;

import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.AbstractDocument;


import DBConnection.*;
import java.sql.*;
import VLSObjects.*;


public class TransactionNew extends JPanel {
    
JTextField plateNumber;
JComboBox manufacturer;
JComboBox model;
JComboBox services;



ImageIcon notice_green = new ImageIcon("images/prompt_notice_green.png");
ImageIcon ask_red = new ImageIcon("images/prompt_ask_red.png");
ImageIcon notice_red = new ImageIcon("images/prompt_notice_red.png");

String blank = "";
String manufacturerSelected; 
String string[] = new String[5];
String modelSet[];

DefaultTableModel model2;

JButton submitButton;
JButton cancelButton;
JButton addButton;

JLabel plateNumberLabel;
JLabel manufacturerLabel;
JLabel modelLabel;
JLabel servicesLabel;
JLabel newTransactionLabel;
JLabel servicesLael;
JLabel currentServicesLabel;
JLabel total;

JScrollPane currentScroll;
JTable currentTable;
    

int z;
int added = 1;
int lent = 0;


public TransactionNew(final JFrame frame){
    
    setVisible(false);
    setLayout (null);
    setBackground(null);
    
    DocumentFilter filter = new UppercaseDocumentFilter();
    
    plateNumber = new JTextField();
    ((AbstractDocument) plateNumber.getDocument()).setDocumentFilter(filter);
    manufacturer = new JComboBox();

    model = new JComboBox();
    
    services = new JComboBox();
     
    submitButton = new JButton();
    cancelButton = new JButton();
    addButton = new JButton();
    
    plateNumberLabel = new JLabel ("Plate Number:");
    manufacturerLabel = new JLabel ("Manufacturer:");
    modelLabel = new JLabel("Model:");
    newTransactionLabel = new JLabel ("NEW TRANSACTION");
    servicesLabel = new JLabel("Services:");
    currentServicesLabel = new JLabel("Current Services");
    total = new JLabel("Total: 0");
    
    newTransactionLabel.setFont(new Font ("sansserif", Font.PLAIN, 40));
    newTransactionLabel.setBounds(10,10,500,30);
    
    plateNumberLabel.setBounds(45,50,150,20);
    manufacturerLabel.setBounds(45,75,150,20);
    modelLabel.setBounds(45,100,150,20);
    servicesLabel.setBounds(45,125,150,20);
    total.setBounds(338,150,150,20);
    
    
    plateNumber.setBounds(130,50,200,20);
    manufacturer.setBounds(130,75,200,20);
    model.setBounds(130, 100, 200, 20);
    services.setBounds(130, 125, 125, 20);
    
    plateNumber.setBorder(null);
    manufacturer.setBorder(null);
    model.setBorder(null);
    
    submitButton.setText("Submit");
    cancelButton.setText("Clear");
    addButton.setText("Add");
   
    
    submitButton.setBounds(175,150,75,20);
    cancelButton.setBounds(255,150,75,20);
    addButton.setBounds(255, 125, 75, 20);
    
    //table codes
    Object headers[] = {"Service", "Price"};
    final Object dummyData[][] = {};
    
    
    currentTable = new JTable();
    currentTable.setModel(new javax.swing.table.DefaultTableModel(dummyData, headers
        ) {

        public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        });
    
    currentScroll = new JScrollPane();
    
    model2 = (DefaultTableModel)currentTable.getModel();
    currentTable.getTableHeader().setReorderingAllowed(false);
    currentScroll.setViewportView(currentTable);
    currentScroll.setBounds(338, 50, 250, 95);
    currentTable.setAutoCreateRowSorter(true);
    
    resetValues();
    
    add(plateNumber);
    add(manufacturer);
    add(model);
    add(services);
    add(plateNumberLabel);
    add(manufacturerLabel);
    add(modelLabel);
    add(servicesLabel);
    add(submitButton);
    add(cancelButton);
    add(addButton);
    add(newTransactionLabel);
    add(currentScroll);
    add(total);
    
                    
    manufacturer.removeAllItems();
    manufacturer.addItem("");
                try{
                    ConnectionFactory myFactory = ConnectionFactory.getFactory();
                    Connection conn = myFactory.getConnection();

                    

                    PreparedStatement pstmt = conn.prepareStatement("SELECT manufacturer FROM vehiclelist GROUP BY manufacturer");

                    ResultSet rs = pstmt.executeQuery();

                    while(rs.next())
                    {
                        manufacturer.addItem(rs.getString(1));
                    }
                    conn.close();
                }   

                catch(SQLException e)
                {
                   e.printStackTrace();
                }
            
    
    manufacturer.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {         
                 enableCombo();   

            }
        }
        );
    
    model.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                
                 if(model.getSelectedItem() != "")
                 {
                     services.setEnabled(true);
                     services.removeAllItems();
                     
                     services.addItem("");
                        try{
                                ConnectionFactory myFactory = ConnectionFactory.getFactory();
                                Connection conn = myFactory.getConnection();

                                

                                PreparedStatement pstmt = conn.prepareStatement("SELECT servicelist.serviceName, servicelist.size FROM vehiclelist JOIN servicelist ON vehiclelist.size = servicelist.size WHERE vehiclelist.model =  '"+ (String)model.getSelectedItem() +"' AND servicelist.available =  'Yes' ORDER BY vehiclelist.model, servicelist.serviceName");

                                ResultSet rs = pstmt.executeQuery();

                                while(rs.next())
                                {
                                    services.addItem(rs.getString(1));
                                    
                                }
                                conn.close();
                            }   

                       catch(SQLException ee)
                            {
                               ee.printStackTrace();
                            }
                 }
                 else if(model.getSelectedItem() == "")
                {   services.setEnabled(false);
                    services.setSelectedItem("");
                }
            }
        }
        );
    
    
    
    plateNumber.addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
          
    
            if (e.getKeyCode()==KeyEvent.VK_BACK_SPACE)
                lent = plateNumber.getText().length() - 1; 
            else
                lent = plateNumber.getText().length() + 1; 
            String text = plateNumber.getText();


            if(plateNumber.getText().length()== 3 && lent == 4 )
            {       

                    plateNumber.setText(text + "-");
            }
            else 
            if(plateNumber.getText().length()== 3 && lent == 2 )
            {       

                   plateNumber.setText(plateNumber.getText().substring(0,2)); 
            }

      }

      public void keyTyped(KeyEvent e) {
      }

      public void keyPressed(KeyEvent e) {
      }
    });
    

    
    submitButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                added = 1;               
                string[0] = plateNumber.getText();
                string[1] = (String)manufacturer.getSelectedItem();
                string[2] = (String)model.getSelectedItem();
                string[3] = (String)services.getSelectedItem();
                
                if(string[0].length() == 0 && string[1] == blank && string[2] == blank)
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                    
                } 
                else if(string[0].length()== 0 || string[1] == blank || string[2] == blank)
                {
                    checkEmpty();
                    if(string[0].length()!= 0 && isPlate(plateNumber.getText()) == false)                        
                        JOptionPane.showMessageDialog(frame,
                                        "Invalid and Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                   
                    else if(string[0].length() == 0 || string[1] == blank || string[2] == blank || isPlate(plateNumber.getText()) == true)
                    JOptionPane.showMessageDialog(frame,
                                        "Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                    
                }   
                else if(isPlate(plateNumber.getText()) == false)
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Invalid Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);

                     
                }            
                else if(isPlate(plateNumber.getText()) == true && string[1] != blank && string[2] != blank)   
                {
                    int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Proceed with current values?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);
                    
                    if(n==0)
                    {
                        added = n;

                        Transaction newTransaction = new Transaction();
                        TransactionManager newTransactionManager = new TransactionManager();
                        ServicesPerTransaction newSPT = new ServicesPerTransaction();
                        ServicesPerTransactionManager newSPTManager = new ServicesPerTransactionManager();
                        VehicleManager newVM = new VehicleManager();
                        ServiceManager newSM = new ServiceManager();
                        
                        
                        newTransaction.setPlateNumber(plateNumber.getText()); //sa transactionManager nalang yung date and time
                        boolean result = newTransactionManager.addTransaction(newTransaction); 

                            for(int i =0; i < model2.getRowCount(); i++)
                        {   newSPT.setTransactionID(newTransactionManager.getLastTransactionID());
                            newSPT.setVehicleID(newVM.getVehicleID((String)model.getSelectedItem()));
                            newSPT.setServiceID(newSM.getServiceID((String)model2.getValueAt(i, 0)));
                            newSPT.setServiceName((String)model2.getValueAt(i, 0));
                            newSPT.setAmount(Integer.parseInt((String)model2.getValueAt(i, 1)));

                            result = newSPTManager.addServicePerTransction(newSPT);
                            
                        }
                        
                        
                        resetValues();
                        if(result == true)
                        {
                            JOptionPane.showMessageDialog(frame,
                                    "Transaction Added!",
                                    "Vehicle Logging Service",
                                    JOptionPane.WARNING_MESSAGE,
                                        notice_green);}
                        
                    }
                    
                    
                }
            }
        }
        );
    
    addButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                if(services.getSelectedItem() == blank)
                {
                    JOptionPane.showMessageDialog(frame,
                                    "Please select Service to Add!",
                                    "Vehicle Logging Service",
                                    JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                }
                else
                {   int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Add Service?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,ask_red);
                 if(n==0)
                    {
                        
                        try{
                                ConnectionFactory myFactory = ConnectionFactory.getFactory();
                                Connection conn = myFactory.getConnection();

                                

                                PreparedStatement pstmt = conn.prepareStatement("SELECT servicelist.serviceName, servicelist.service_amount FROM vehiclelist JOIN servicelist ON vehiclelist.size = servicelist.size WHERE vehiclelist.model = '"+ (String)model.getSelectedItem() +"' AND servicelist.serviceName = '"+ (String)services.getSelectedItem() +"' ORDER BY vehiclelist.model, servicelist.serviceName");

                                ResultSet rs = pstmt.executeQuery();

                                while(rs.next())
                                {
                                    model2.addRow(new Object[]{rs.getString(1), rs.getString(2)});
                                }
                                conn.close();
                                
                                services.removeItem((String)services.getSelectedItem());
                                services.setSelectedItem("");
                            }   

                       catch(SQLException ee)
                            {
                               ee.printStackTrace();
                            }
                             int tot = 0;
                    for(int i = 0; i<currentTable.getRowCount(); i++)
                    {
                            int wow = Integer.parseInt((String)model2.getValueAt(i, 1));
                            tot = tot + wow;
                    }
                total.setText("Total: "+tot);           
                        JOptionPane.showMessageDialog(frame,
                                    "Service Added",
                                    "Vehicle Logging Service",
                                    JOptionPane.WARNING_MESSAGE,
                                        notice_green);
                    }
                    
                }
                
             
            }
        }
        );
    
    cancelButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                 int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Are you sure you want to clear the values?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,ask_red);
               if(n==0)
                    { 
                resetValues();            
                    }
               
            }
        }
        );
    
    }
    
    public void checkEmpty()
    {   
        String s = "";
       
        if(plateNumber.getText().length() == 0)
            plateNumber.setBackground(Color.YELLOW);
               
        else if(isPlate(plateNumber.getText()) == false)
            plateNumber.setBackground(Color.RED);
        
        if(isPlate(plateNumber.getText()) == true)
            plateNumber.setBackground(null);
        
        if((String)manufacturer.getSelectedItem() == s)
            manufacturer.setBackground(Color.YELLOW);
        
        if((String)model.getSelectedItem() == s)
            model.setBackground(Color.YELLOW);
        
        if((String)manufacturer.getSelectedItem() != s)
            manufacturer.setBackground(null);
        
        if((String)model.getSelectedItem() != s)
            model.setBackground(null);
        
    }
    
    public void resetValues()
    {
        plateNumber.setBackground(null);
        manufacturer.setBackground(null);
        model.setBackground(null);
        services.setBackground(null);
        
        model.setEnabled(false);
        services.setEnabled(false);
        
        plateNumber.setText("");
        manufacturer.setSelectedItem("");
        model.setSelectedItem("");
        services.setSelectedItem("");
        model2.setRowCount(0); 
    
       
    }
    
    public boolean isPlate(String x)
    {
        char[] check = x.toCharArray();        
        if(check.length == 7)
            {
            if(Character.isLetter(check[0]) && Character.isLetter(check[1]) && Character.isLetter(check[2]) && check[3] == '-' && Character.isDigit(check[4]) && Character.isDigit(check[5]) && Character.isDigit(check[6]))
            {       

                return true;
            }         
            else
                return false;
            }
        else
           return false;
    }
    

    class UppercaseDocumentFilter extends DocumentFilter {
        public void insertString(DocumentFilter.FilterBypass fb, int offset,String text, AttributeSet attr)

        throws BadLocationException {



        fb.insertString(offset, text.toUpperCase(), attr);

        }
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length,String text, AttributeSet attrs)

        throws BadLocationException {

        fb.replace(offset, length, text.toUpperCase(), attrs);

        }
    }
    
    public void enableCombo()
    {
        if(manufacturer.getSelectedItem() != "")
        {
            model.removeAllItems();
            model.addItem("");
            model.setEnabled(true);
            manufacturerSelected = (String)manufacturer.getSelectedItem();
            
                try{
                    ConnectionFactory myFactory = ConnectionFactory.getFactory();
                    Connection conn = myFactory.getConnection();

                    int i = 1;

                    PreparedStatement pstmt = conn.prepareStatement("SELECT model FROM vehiclelist WHERE manufacturer = ?");

                    pstmt.setString(i++, manufacturerSelected);

                    ResultSet rs = pstmt.executeQuery();

                    while(rs.next())
                    {  
                        model.addItem(rs.getString(1));
                    }
                    conn.close();
                }   

            catch(SQLException e)
            {
               e.printStackTrace();
            }
            
        }
                
        else if(manufacturer.getSelectedItem() == "")
        {
            model.setEnabled(false);
            services.setEnabled(false);
            model.setSelectedItem("");
            services.setSelectedItem("");
        }
        
    }

}
